// pages/invitation/invitation.js
var app = getApp();
var page_s = 1;
var imgpage = 1;
var goldpage = 1;
var pageSize = 20;
var upimg = '';
var imgggg = '';
var is_open = false; //开关
Page({

        /**
         * 页面的初始数据
         */
        data: {
            backImg: '', // headimg,//设备列表
            w_idth: 0, //手机宽度
            h_eight: 0, //手机高度
            curr_index: 0, //展示的
            usermagInfo: '', //用户信息
            user_id: '', //用户id
            code_qr: '', //当前二维码
            arrlist: [], //模拟数据
            showmodel: false, //选择弹窗盒子
            aniStyle: false, //选择控制动画
            stepOne: false, //编辑盒子
            oneain: false, //第一步动画
            shooseindex: 0, //第一步选择的图片
            shoosepicture: '', //自定义的图片
            arrImg: [], //自定义图片列表
            goldlist: [], //金句列表
            pictureWay: 1, //1选择模板图片  2自定义图片
            stepTwo: false, //第二步盒子
            twoAin: false, //第二部动画
            tabway: 0, //0是金句  1自己输入
            radioval: 0, //选中的金句值
            tarVal: '', //自己输入的值
            showCanvas: false, //canvas盒子
            popshow: false, //canvas 盒子动画
            showShare: false,

        },

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function(options) {
            var that = this;
            var user_id = wx.getStorageSync('user_id');
            wx.getSystemInfo({
                    success: function(res) {
                        that.setData({
                            w_idth: res.windowWidth,
                            h_eight: res.windowHeight,
                            user_id: user_id
                        })

                    },
                })
                // wx.showLoading({
                //   title: '即将开放',
                // })
            that.getUserInfo(); //获取用户信息
            page_s = 1;
            imgpage = 1;
            goldpage = 1;
            that.getSharing(page_s); //获取模板
            that.getImage(imgpage); //自定义图片
            that.getgoldshow(goldpage); //金句列表

        },

        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady: function() {

        },
        //获取---模本列表(搭建好的)  	 
        getSharing(page_s) {
            var that = this;
            app.ajax({
                url: 'User/Share/getSharing',
                method: "POST",
                data: {
                    page: page_s,
                    pageSize: pageSize
                },
                success: function(res) {
                    if (res.data.code == 1000) {
                        that.setData({
                            arrlist: res.data.data
                        })
                        let u_id = that.data.user_id;
                        let lin_k = res.data.data[0].link;
                        that.getcodeImg(u_id, lin_k); //生成二维码
                    } else {
                        app.showToast(res.data.message, "none", 2000, function() {});
                    }
                    wx.hideLoading();
                }

            })
        },
        //获取----专属二维码
        getcodeImg(u_id, lin_k) {
            var that = this;
            var pro = wx.getStorageSync('promoter') || 1;
            var cha = wx.getStorageSync('channel') || 1;
            app.ajax({
                url: 'Common/Wx/getPageQr',
                method: "POST",
                data: {
                    query: "pid=" + u_id + "&pro=" + pro + "&cha=" + cha + "&way=2",
                    page: lin_k,
                },
                success: function(res) {
                    if (res.data.code == 1000) {
                        that.setData({
                            code_qr: res.data.data.all_url
                        })
                        that.downLoadImg(res.data.data.all_url, 'code_img'); //缓存二维码图片 不用下载文件
                    } else {
                        app.showToast(res.data.message, "none", 2000, function() {});
                    }
                    wx.hideLoading();
                    is_open = false;
                }

            })
        },
        //获取----自定义图片列表
        getImage(imgpage) {
            var that = this;
            app.ajax({
                url: 'User/Share/getImage',
                method: "POST",
                data: {
                    page: imgpage,
                    pageSize: pageSize,
                },
                success: function(res) {
                    if (res.data.code == 1000) {
                        upimg = res.data.data[0].image
                        that.setData({
                            arrImg: res.data.data,
                            shoosepicture: res.data.data[0].image,
                            shooseindex: 0
                        })
                    } else {
                        //  app.showToast(res.data.message, "none", 2000, function () { });
                    }
                    wx.hideLoading();
                }

            })
        },
        //获取----自定义金句列表
        getgoldshow(goldpage) {
            var that = this;
            app.ajax({
                url: 'User/Share/getSentence',
                method: "POST",
                data: {
                    page: imgpage,
                    pageSize: pageSize,
                },
                success: function(res) {
                    if (res.data.code == 1000) {
                        that.setData({
                            goldlist: res.data.data,
                        })
                    } else {
                        // app.showToast(res.data.message, "none", 2000, function () { });
                    }
                    wx.hideLoading();
                }

            })
        },
        //获取用户信息
        getUserInfo() {
            var that = this;
            app.ajax({
                url: "User/User/getUser",
                data: {},
                success: function(res) {
                    if (res.data.code == 1000) {
                        that.setData({
                            usermagInfo: res.data.data,
                            user_id: res.data.data.user_id
                        })
                        wx.setStorageSync('user_id', res.data.data.user_id)

                        wx.getImageInfo({
                            src: res.data.data.headimg,
                            success: function(res) {
                                //请求成功后将会生成一个本地路径即res.path,只存 codeimg 和 背景图片.....
                                wx.setStorageSync("userImg", res.path);
                            }
                        })
                    } else {
                        //app.showToast(res.data.message, "none", 2000, function () { });
                    }
                }
            })
        },
        //开始画图像...
        ondraw(back_imgss, code_imgss, text_s, auts, time) {
            // console.log('图片', back_imgss);
            // console.log('二维码', code_imgss);
            // console.log('文字', text_s);
            // console.log('作者', auts);
            // console.log('time', time);
            //return false;
            var that = this;
            let change = that.data.usermagInfo.wx_nickname_code;
            // var username ='';
            // if (change.length>=7){
            //   username = change.substring(0,2) + '...' + change.substring(change.length - 2);
            // }else{
            //   username = change;
            // }
            var context = wx.createCanvasContext('myCanvas');
            let w_h = that.data.w_idth;
            let h_t = that.data.h_eight;
            let backImg = wx.getStorageSync('back_img');
            let QHimg = wx.getStorageSync('code_img');
            let user_img = wx.getStorageSync('userImg');
            let code_w = h_t * 0.96 * 0.08; //二维码宽度
            //时间
            let myDate = new Date();
            let year = myDate.getFullYear()
            let mon = myDate.getMonth() + 1;
            let month = 10 <= mon ? mon : "0" + mon;
            let day = 10 <= myDate.getDate() ? myDate.getDate() : '0' + myDate.getDate();
            let wDay = myDate.getDay();
            let hour = myDate.getHours()
            let minute = 10 <= myDate.getMinutes() ? myDate.getMinutes() : '0' + myDate.getMinutes();
            let second = myDate.getSeconds()
            let weekArray = ['天', '一', '二', '三', '四', '五', '六'];
            let weekday = weekArray[wDay];
            let author = auts ? '─ ─ ' + auts : '';

            //白色盒子
            // context.fillStyle='#fff';
            // context.fillRect(0, 0, w_h * 0.8, h_t * 0.96 * 0.8); //end
            //背景图片
            context.drawImage(backImg, 0, 0, w_h * 0.8, h_t * 0.96 * 0.8);
            //头像
            // context.arc(40, 40, 5, 0, 2 * Math.PI);
            // context.clip();
            // context.drawImage(user_img, 20, 20, 5, 5);

            context.drawImage(user_img, 20, 20, code_w * 0.7, code_w * 0.7);
            //白色盒子
            // context.fillStyle='white';
            // context.fillRect(0, h_t * 0.96 * 0.8 * 0.855, w_h, h_t * 0.96 * 0.8 * 0.145);
            //二维码
            context.drawImage(QHimg, w_h / 10.2, h_t * 0.96 * 0.8 * 0.86 - 15, code_w, code_w);
            //邀请人
            context.font = '14px  serif';
            context.setTextAlign('left');
            context.fillStyle = 'rgb(47,151,212)';
            context.fillText(change, (code_w * 0.7 + 30), 40);
            //优净云
            // context.font = '12px cursive';
            // context.setTextAlign('left');
            // context.fillStyle = 'rgb(40,27,18)';
            // // context.fillText('12万用户的共同选择', (code_w * 0.7 + 30), 50);
            // context.stroke();
            //优净云
            context.save();
            context.beginPath();
            context.font = '11px  serif';
            context.fillStyle = 'rgb(0,0,0)';
            context.setTextAlign('center');
            context.fillText('长按识别立即预订', w_h / 6.5, h_t * 0.96 * 0.8 * 0.99 - 10);
            //作者
            // context.font = '14px cursive';
            // context.fillStyle = 'rgb(255,255,255)';
            // context.setTextAlign('right');
            // context.fillText(author, w_h / 1.3, h_t * 0.96 * 0.6);
            //时间   year + '-' + month + '-' + day + ' ' + '星期' + weekday
            // context.font = '14px sans-serif';
            // context.setTextAlign('right');
            // context.fillStyle = 'rgb(255,255,255)';
            // context.fillText(time, w_h / 1.3, h_t * 0.96 * 0.64);

            //简介
            // context.font = '16px Arial';
            // context.setTextAlign('left');
            // context.fillStyle = 'rgb(255,255,255)';
            // // context.fillText(texts, w_h*0.1, h_t * 0.96 * 0.45);
            // let text_content = text_s; //这是要绘制的文本
            // let sptext = text_content.split(""); //这个方法是将一个字符串分割成字符串数组
            // let temps = "";
            // let rows = [];
            // let box_w_w = w_h * 0.8 * 0.9;
            // for (let i = 0; i < sptext.length; i++) {
            //   if (context.measureText(temps).width < (box_w_w - (w_h - box_w_w) / 2)) {
            //     temps += sptext[i];
            //   } else {
            //     i--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
            //     rows.push(temps);
            //     temps = "";
            //   }
            // }
            // rows.push(temps);
            // let top_h = h_t * 0.96 * 0.45 + (4 - rows.length)*25;//简介高度
            // for (let b = 0; b < rows.length; b++) {
            //   context.fillText(rows[b], (w_h - box_w_w) / 3, top_h + b * 25);
            // }

            context.draw(true);
            wx.hideLoading();
            that.setData({
                showShare: true
            })
        },
        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function() {

        },

        /**
         * 生命周期函数--监听页面隐藏
         */
        onHide: function() {

        },

        /**
         * 生命周期函数--监听页面卸载
         */
        onUnload: function() {

        },
        /**
         * 用户点击右上角分享
         */
        onShareAppMessage: function(res) {
            this.shareLogFun(1); //记录
            var user_id = wx.getStorageSync('user_id');
            var pro = wx.getStorageSync('promoter') || 1;
            var cha = wx.getStorageSync('channel') || 1;
            return {
                title: '我发现了一个好用的生活小工具，快来加入哟',
                path: 'pages/home/home?pid=' + user_id + "&way=1&pro=" + pro + "&cha=" + cha
            }
        },
        //canvas 报错事件
        canvasIdErrorCallback: function(e) {
            console.error(e.detail.errMsg)
        },
        //选择某张图片
        chooseit(e) {
            var that = this;
            if (is_open) {
                app.showToast('正在生成二维码');
                return false;
            }
            is_open = true;
            let index = e.currentTarget.dataset.index;
            let userid = e.currentTarget.dataset.userid;
            let lin_k = e.currentTarget.dataset.link;
            that.getcodeImg(userid, lin_k); //生成二维码
            that.setData({
                    curr_index: index
                })
                // if (userid != 0 && userid != undefined) {
                //   that.redactImg();
                //   return;
                // } else {

            // }
        },

        //调起分享
        Invitation: function() {
            var that = this;
            that.setData({
                showmodel: true,
                aniStyle: true,
            })
        },
        //隐藏分享卡片
        cancel() {
            var that = this;
            that.setData({
                aniStyle: false,
            })
            setTimeout(function() {
                that.setData({
                    showmodel: false,
                })
            }, 401)
        },
        // 选择第一步打开盒子
        redactImg() {
            var that = this;
            that.setData({
                showmodel: false,
                aniStyle: false,
                stepOne: true,
                oneain: true
            })

        },
        //关闭第一步
        can_it() {
            var that = this;
            that.setData({
                oneain: false,
            })
            setTimeout(function() {
                that.setData({
                    stepOne: false,
                })
            }, 401)
        },
        //选择本地图片
        phoneImg() {
            var that = this;
            wx.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album'],
                success(res) {
                    // tempFilePath可以作为img标签的src属性显示图片
                    const tempFilePaths = res.tempFilePaths
                    const newUrl = tempFilePaths[0];
                    that.uplodImg(newUrl);
                }
            })
        },
        //上传图片到服务器
        uplodImg(chengimg) {
            var that = this;
            wx.showLoading({
                title: '上传图片中',
            })
            wx.uploadFile({
                url: app.globalData._url + 'Common/Common/upload',
                filePath: chengimg,
                name: 'file',
                success: function(res) {
                    var data = JSON.parse(res.data);
                    if (data.code == 1000) {
                        upimg = ''; //置空
                        upimg = data.data.url;
                        that.setData({
                            shoosepicture: data.data.all_url,
                            pictureWay: 2
                        })
                        that.addImage(data.data.all_url); //上传图片
                    } else {
                        app.showToast("上传图片失败");
                    }
                    wx.hideLoading();
                },
                complete: function() {

                },
                fail: function() {
                    app.showToast("上传图片失败,请重试");
                }
            })
        },
        addImage(updata) {
            var that = this;
            app.ajax({
                url: 'User/Share/addImage',
                method: "POST",
                data: {
                    image: updata,
                },
                success: function(res) {
                    if (res.data.code == 1000) {
                        imgpage = 1;
                        that.getImage(imgpage); //自定义图片
                    } else {
                        app.showToast(res.data.message, "none", 2000, function() {});
                    }
                    wx.hideLoading();
                }

            })
        },
        //选择第一步图片
        shooseImg(e) {
            var that = this;
            let in_dex = e.currentTarget.dataset.index;
            upimg = e.currentTarget.dataset.imageurl;
            let currimg = that.data.arrImg[in_dex].image;
            that.setData({
                shooseindex: in_dex,
                shoosepicture: currimg,
                pictureWay: 1
            })
        },
        //下一步
        nextStep() {
            var that = this;
            that.setData({
                stepTwo: true,
                twoAin: true,
            })
            setTimeout(function() {
                that.setData({
                    // oneain: false,
                    stepOne: false,
                })
            }, 401)
        },
        //上一步
        upstpe() {
            var that = this;
            that.setData({
                stepOne: true,
                stepTwo: false,
                twoAin: false,
            })
        },
        //一键生成
        completefun() {
            var that = this;
            let p_Way = that.data.pictureWay; //自定图片 还是 模板
            let tab_way = that.data.tabway; //金句0 or 自定文字1  
            let tar_Val = that.data.tarVal; //自己输入的内容
            let in_val = that.data.radioval; //金句选中的值
            let gold_list = that.data.goldlist; //金句
            let up_text = '';
            let up_author = '';
            let up_time = '';

            if (upimg == '') {
                app.showToast('所选模板图片有误,请重选', "none", 3000, function() {});
                return false;
            }
            // if (tab_way == 1 && tar_Val==''){
            //   app.showToast('所选模板图片有误,请重选', "none", 3000, function () { });
            //   return false;
            // }
            if (tab_way == 1) {
                up_text = tar_Val;
            } else {
                up_text = gold_list[in_val].content;
                up_author = gold_list[in_val].author;
                up_time = gold_list[in_val].time;
            }
            app.ajax({
                url: 'User/Share/addSharing',
                method: "POST",
                data: {
                    image: upimg,
                    sentence: up_text,
                    author: up_author,
                    time: up_time,
                    link: 'pages/home/home'
                },
                success: function(res) {
                    if (res.data.code = 1000) {
                        app.showToast(res.data.message, "none", 2000, function() {});
                        page_s = 1;
                        that.getSharing(page_s); //重新----获取模板
                        that.setData({
                            oneain: false,
                            stepOne: false,
                            twoAin: false,
                            curr_index: 0
                        })
                        setTimeout(function() {
                            that.setData({
                                stepTwo: false,
                            })
                        }, 401)
                    } else {
                        app.showToast(res.data.message, "none", 2000, function() {});
                    }
                }

            })

        },
        //选中的table 金句or自己
        ontable(e) {
            var that = this;
            let tabway = e.currentTarget.dataset.ways;
            that.setData({
                tabway: tabway
            })
        },
        //选择金句
        sentence(e) {
            var that = this;
            let ind_ex = e.currentTarget.dataset.index;
            that.setData({
                radioval: ind_ex
            })
        },
        //textareainput输入
        tarInput(e) {
            var that = this;
            let val = e.detail.value;
            that.setData({
                tarVal: val
            })
        },
        //生成 本地图片保存到手机.. 
        sharebtn() {
            var that = this;
            let w_idth = that.data.w_idth;
            let h_eight = that.data.h_eight;
            setTimeout(function() {
                wx.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    fileType: 'jpg',
                    success: function(res) {
                        wx.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success(res) {
                                wx.hideLoading();
                                wx.showToast({
                                    title: '保存成功',
                                });
                                that.shareLogFun(2); //获取记录
                            },
                            fail() {
                                wx.hideLoading()
                            }
                        })
                    },
                    fail(res) {
                        console.log('失败了', res);
                    }
                })
            }, 500);
        },
        //打开 动画...canvas加载动画
        popBtn() {
            var that = this;
            var arr_list = that.data.arrlist;
            let codimg = that.data.code_qr;
            let index = that.data.curr_index;
            let baks = arr_list[index].image;
            let tes = arr_list[index].sentence;
            let auts = arr_list[index].author;
            let time = arr_list[index].time;
            that.downLoadImg(baks, 'back_img'); //缓存背景图片 不用下载文件
            that.setData({
                showmodel: false,
                aniStyle: false,
                popshow: true,
                showCanvas: true,
            })
        },
        //将网络图片存缓存 然后保存
        downLoadImg(netUrl, storageKeyUrl) {
            var that = this;
            var arr_list = that.data.arrlist;
            let codimg = that.data.code_qr;
            let index = that.data.curr_index;
            let baks = arr_list[index].image;
            let tes = arr_list[index].sentence;
            let auts = arr_list[index].author;
            let time = arr_list[index].time;
            if (storageKeyUrl == 'back_img') {
                wx.showLoading({
                    title: '正在生成...',
                });
            }
            wx.getImageInfo({
                src: netUrl,
                success: function(res) {
                    //请求成功后将会生成一个本地路径即res.path,只存 codeimg 和 背景图片.....
                    // console.log('结果', res.path, '???????????',storageKeyUrl);
                    wx.setStorageSync(storageKeyUrl, res.path);
                    if (storageKeyUrl == 'back_img') {
                        that.ondraw(baks, codimg, tes, auts, time);
                    }

                }
            })
        },
        //关闭盒子动画
        shutBtn() {
            var that = this;
            that.setData({
                popshow: false
            })
            setTimeout(function() {
                that.setData({
                    showCanvas: false,
                })
            }, 401)
        },
        //分享记录
        shareLogFun(s_way) {
            var that = this;
            app.ajax({
                url: 'User/Share/shareLog',
                method: "POST",
                data: { type: 1, share_way: s_way }, //1是邀请好友 2分享详情 
                success: function(res) {
                    if (res.data.code = 1000) {

                    } else {

                    }
                }

            })
        },
    })
    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {
    //   var that=this;
    //   var user_id = that.data.user_id;
    //   return {
    //     title: '',
    //     path: '/pages/home/home?inviter_id=' + user_id
    //   }
    // },